﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Util;
using IntroduceCompany.Singleton;
using System.IO;
using IntroduceCompany.Models;

namespace IntroduceCompany.Controllers
{
    [HandleError]
    [CheckModule(ConstantClass.Backend_Video_MenuID)]
    public class VideoController : BaseController
    {

   #region BackEnd_Video

        [Authorize(Roles = ConstantClass.autVideo)]
        public ActionResult VideoList()
        {
            string languageID = ConstantClass.markViewAllLanguage;
            if (Request.Cookies[ConstantClass.cooLanguage] != null && Request.Cookies[ConstantClass.cooLanguage].Value != "")
            {
                languageID = Request.Cookies[ConstantClass.cooLanguage].Value;
            }

            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);
            return View("/Views/Backend/Video/VideoList.aspx", DataSingleton.GetVideoModels().GetVideo(languageID));
        }

        /// <summary>
        /// Change video Status that is visible or invisible
        /// </summary>
        /// <param name="videoID"></param>
        /// <param name="videoVisible"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autVideo)]
        public ActionResult ChangeVideoVisible(int videoID, bool videoVisible)
        {
            if (ModelState.IsValid)
            {
                DataSingleton.GetVideoModels().ChangeVideoVisible(videoID, videoVisible);
            }
            return RedirectToAction("videoList", "Video");
        }

        [Authorize(Roles = ConstantClass.autVideo)]
        [ValidateInput(false)]
        [ActionName("Edit")]
        public ActionResult VideoEdit(int videoID, String languageID)
        {
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);//languageID
            VideoView oneVideoView = DataSingleton.GetVideoModels().GetVideoByVideoIDAndLanguageID(videoID, languageID);
            if (oneVideoView == null)
            {
                oneVideoView = new VideoView();
                Video video = DataSingleton.GetVideoModels().GetVideoByID(videoID);
                oneVideoView.Username = video.UserName;
                oneVideoView.VideoURL = video.VideoURL;
                oneVideoView.VideoVisible = video.VideoVisible;
            }
            return View("/Views/Backend/Video/VideoEdit.aspx", oneVideoView);
        }

        [Authorize(Roles = ConstantClass.autVideo)]
        [HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult VideoEdit(VideoView _EditedVideoView, String linkURL)
        {
            string username = HttpContext.User.Identity.Name;
            _EditedVideoView.Username = username;
            VideoView oneVideoView = DataSingleton.GetVideoModels().GetVideoByVideoIDAndLanguageID(_EditedVideoView.VideoID, _EditedVideoView.LanguageID);

            if (linkURL.ToString() != "")
            {
                _EditedVideoView.VideoURL = DataSingleton.GetVideoModels().CutVideoURL(linkURL);
                if (_EditedVideoView.VideoURL.ToString() != "")
                {
                    DataSingleton.GetVideoModels().UpdateVideoLinkCode(_EditedVideoView);
                }
                else 
                {
                    ModelState.AddModelError("Notice", "Video link không hợp lệ.");
                }
            }

            if (oneVideoView != null)// the video has this language so update only
            {
                if (ModelState.IsValid)
                {
                    
                    DataSingleton.GetVideoModels().VideoEdit(_EditedVideoView);
                    ModelState.Clear();
                    ModelState.AddModelError("Notice", "Thông tin cập nhật thành công.");
                }
            }
            else// the video do not has this language so insert new language
            {
                if (ModelState.IsValid)
                {
                    DataSingleton.GetVideoModels().Video_L_Create(_EditedVideoView.VideoID, _EditedVideoView.LanguageID, 
                        _EditedVideoView.VideoTitle, _EditedVideoView.VideoDescription);
                    ModelState.AddModelError("Notice", "Thêm ngôn ngữ mới thành công.");
                }
            }
            _EditedVideoView.VideoDate = DateTime.Now;
            _EditedVideoView.FullName = DataSingleton.GetInstance().Administrators.SingleOrDefault(u => u.UserName == username).FullName;
             ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", _EditedVideoView.LanguageID);
             return View("/Views/Backend/Video/VideoEdit.aspx", _EditedVideoView);
       //      return RedirectToAction("VideoEdit", "Video", new { videoID = _EditedVideoView.VideoID, languageID = _EditedVideoView.LanguageID });
            
        }

        [Authorize(Roles = ConstantClass.autVideo)]
        public ActionResult VideoCreate()
        {
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");
            return View("/Views/Backend/Video/VideoCreate.aspx");
        }

        [Authorize(Roles = ConstantClass.autVideo)]
        [HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt, Order = 2)]
        public ActionResult VideoCreate(VideoView _NewOneVideo)
        {
            int albumMaxID = 0;
            _NewOneVideo.Username = HttpContext.User.Identity.Name;
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");

            if (ModelState.IsValid)
            {
                _NewOneVideo.VideoURL = DataSingleton.GetVideoModels().CutVideoURL(_NewOneVideo.VideoURL);
                if (_NewOneVideo.VideoURL.ToString() != "")
                {
                    albumMaxID = DataSingleton.GetVideoModels().VideoCreate(_NewOneVideo);

                    DataSingleton.GetVideoModels().Video_L_Create(albumMaxID, _NewOneVideo.LanguageID, _NewOneVideo.VideoTitle, _NewOneVideo.VideoDescription);
                    return RedirectToAction("Edit", "Video", new { videoID = albumMaxID, languageID = _NewOneVideo.LanguageID });
                }
                else 
                {
                    ModelState.AddModelError("Notice", "video Link không không hợp lệ.");
                    return View("/Views/Backend/Video/VideoCreate.aspx");
                }
            }
            else
            {
                return View("/Views/Backend/Video/VideoCreate.aspx");
            }
        }

        [Authorize(Roles = ConstantClass.autVideo)]
        public ActionResult VideoDelete(int videoID)
        {
            DataSingleton.GetVideoModels().VideoDelete(videoID);
            return RedirectToAction("VideoList", "Video");
        }

    #endregion


//////////////////////////////////////////////////////////////////////////////


   #region FrontEnd_Video
       
        public ActionResult Frontend_VideoList(String pageIndex, String video_SEO_URL,String videoMenu_SEO_URL)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            ViewData["pageIndex"] = pageIndex;// temporarily hold pageIndex value to pass to func Frontend_VideoList_Middle
            ViewData["video_SEO_URL"] = video_SEO_URL;
            ViewData["videoMenu_SEO_URL"] = videoMenu_SEO_URL;
            return View("/Views/Frontend/Video/Video.aspx");
        }

        /// <summary>
        /// use in backend , videoList but link to frontend for admin to check quickly
        /// </summary>
        /// <param name="articleSEO_URL"></param>
        /// <returns></returns>
        public ActionResult Frontend_VideoList2(int videoID, String languageID)
        {
            string url = "/" + languageID + "/vid/";
            string videoMenu_SEO_URL = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID
                (ConstantClass._Frontend_Video_MenuID.ToString(), languageID);
            string video_SEO_URL = DataSingleton.GetVideoModels().GetVideo_SEO_URL_By_VideoID_LanguageID(videoID, languageID);
            url += videoMenu_SEO_URL+"/1/" + video_SEO_URL;
            return Redirect(url);
        }

        public ActionResult Frontend_VideoList_Middle(String pageIndex, String video_SEO_URL, String videoMenu_SEO_URL)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            int videoID = 0;
            // when changing paging, the video clip will be the first clip of that page
            if (video_SEO_URL == "")
            {
                try
                {
                    videoID = DataSingleton.GetVideoModels().Frontend_GetOnePageVideo(languageID, pageIndex, ConstantClass.VideoPageStep).FirstOrDefault().VideoID;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    videoID = 0;
                }
            }
            else
            {
                videoID = DataSingleton.GetVideoModels().GetVideoID_By_Video_SEO_URL(video_SEO_URL);
            }
            // when changing paging, the video clip will not change
            //if (pageIndex2 == "1" && videoID == null)
            //{
            //    videoID = DataSingleton.GetVideoModels().Frontend_GetVideo(languageID).FirstOrDefault().VideoID.ToString();
            //}

            if (videoID != 0)
            {
                VideoView videoView_Temp = DataSingleton.GetVideoModels().Frontend_GetVideoByVideoIDAndLanguageID(videoID, languageID);

                if (videoView_Temp != null)
                {
                    ViewData["Video_Title"] = videoView_Temp.VideoTitle;
                    ViewData["Video_URL"] = videoView_Temp.VideoURL;
                    ViewData["Video_Des"] = videoView_Temp.VideoDescription;
                    ViewData["Video_ID"] = videoView_Temp.VideoID;
                    ViewData["Video_languageID"] = videoView_Temp.LanguageID;
                }
                else
                {
                    Video video_temp = DataSingleton.GetVideoModels().Frontend_GetVideoWithoutLanguage(videoID);
                    if (video_temp != null)// video has been set visible=false
                    {
                        ViewData["Video_Title"] = "không có ngôn ngữ này, chỉ có video";
                        ViewData["Video_URL"] = video_temp.VideoURL;
                        ViewData["Video_Des"] = "";
                    }
                }

                ViewData["videoID"] = videoID;// keep the old video when changing the page(used in Middle.ascx)
                ////////////////////////// start paging
                int totalRows = DataSingleton.GetVideoModels().Frontend_GetTotalRowsOneLanguage(languageID);
                int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.VideoPageStep);

                if (pageIndex != "1")
                {
                    ViewData["Previous_Mark_Visibility"] = "true";
                }
                if (totalPages != Convert.ToInt16(pageIndex))
                {
                    ViewData["Next_Mark_Visibility"] = "true";
                }

                ViewData["NextPageIndex"] = (Convert.ToInt16(pageIndex) + 1).ToString();
                ViewData["PreviousPageIndex"] = (Convert.ToInt16(pageIndex) - 1).ToString();
                ViewData["PageIndex"] = pageIndex;
                ////////////////////////// end paging

                return View("/Views/Frontend/Video/Middle.ascx", DataSingleton.GetVideoModels().Frontend_GetOnePageVideo(languageID, pageIndex, ConstantClass.VideoPageStep));
            }
            else
            {
                return View("/Views/Frontend/Video/Middle.ascx", null);
            }
        }

   #endregion

    }
}
